package com.tc.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: tianchao
 * @Date: 2022/2/10 11:18
 * @Description:
 */
@Slf4j
public class HelloServer {
    public static void main(String[] args) {
        // 1 启动器,负责组装netty组件，启动服务器
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //2. BossEventLoop, WorkerEventLoop(selector thread)
        serverBootstrap.group(new NioEventLoopGroup())
                //3 服务器的ServerSocketChannel 实现
                .channel(NioServerSocketChannel.class)
                //4 boss负责处理连接 worker(child)负责处理读写，决定了worker(child)能执行那些操作（handler）
                .childHandler(
                        //5 channel代表和客户端进行数据读写的通道 Initializer初始化，负责添加别的handler
                        new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 6 添加具体 handler
                        ch.pipeline().addLast(new StringDecoder()); //将 ByteBuf转换为字符串
                        // 添加自定义的handler 打印上一步转换好的字符串
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.info("接收到的ChannelHandlerContext: {},数据为: {}",ctx,msg);
                            }
                        });
                    }
                });
        serverBootstrap.bind(8081);
    }
}
